<template>
  <el-dialog
    title="分配权限"
    :visible="showDialog"
    width="30%"
    center
    @close="closeFn"
  >
    <el-tree
      ref="tree"
      :data="data"
      show-checkbox
      default-expand-all
      :props="defaultProps"
      check-strictly
      node-key="id"
    />
    <span slot="footer" class="dialog-footer">
      <el-button plain size="small" @click="closeFn">取 消</el-button>
      <el-button type="primary" plain size="small" @click="confirmFn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listToTree } from '@/utils/index'
import { getPermissionsList } from '@/api/permissions'
import { getRole, editRole } from '@/api/roles'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: [], // 权限列表
      permIds: [], // 选中的权限列表
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      roleId: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    closeFn() {
      this.$emit('update:showDialog', false)
    },
    // 更新权限点
    async confirmFn() {
      // 获取选中的权限集合
      this.permIds = this.$refs.tree.getCheckedKeys()
      // console.log(this.permIds)
      // 调用接口，更新权限
      await editRole({
        id: this.roleId,
        permissions: this.permIds
      })
      this.closeFn()
    },
    // 获取所有权限列表，渲染成树形结构
    async getPermissionList() {
      const res = await getPermissionsList()
      this.data = listToTree(res.data, '0')
    },
    // 数据回显已经选中的权限点
    async getRole(id) {
      this.roleId = id
      const res = await getRole(id)
      this.permIds = res.data.permissions
      this.$refs.tree.setCheckedNodes(this.permIds)
    }
  }
}
</script>

<style>

</style>
